package com.tian.config;

import cn.hutool.core.collection.CollectionUtil;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年06月05日 15:49
 * 博客地址：<a href="http://woaijava.cc/">博客地址</a>
 * <p>
 * 短信验证码
 */
@Configuration
@ConfigurationProperties(prefix = "message")
public class MessageTemplateSingleton {

    private List<Template> templates;

    public static class Template {
        private Integer type;
        private String name;
        private String content;

        public Integer getType() {
            return type;
        }

        public void setType(Integer type) {
            this.type = type;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }

    public List<Template> getTemplates() {
        return templates;
    }

    public void setTemplates(List<Template> templates) {
        this.templates = templates;
    }

    private Map<Integer, Template> templateMap = new ConcurrentHashMap<>();

    public Template getTemplate(int type) {
        if (CollectionUtil.isEmpty(templateMap)) {
            synchronized (this) {
                if (CollectionUtil.isNotEmpty(templateMap)) {
                    return templateMap.get(type);
                }
                templateMap = templates.stream().collect(Collectors.toMap(Template::getType, Function.identity(), (key1, key2) -> key2));
                return templateMap.get(type);
            }
        }
        return templateMap.get(type);
    }
}
